package com.lcf.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.framework.utils.UserUtils;
import com.lcf.framework.vo.PageVO;
import com.lcf.system.dao.GoodsDao;
import com.lcf.system.dao.UserOrderDao;
import com.lcf.system.dto.GoodsDTO;
import com.lcf.system.entity.Goods;
import com.lcf.system.query.GoodsPageQuery;
import com.lcf.system.service.GoodsService;
import com.lcf.system.vo.GoodsVO;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

/**
 * 商品(Goods)表服务实现类
 *
 * @author lcf
 * @since 2025-04-24 21:14:31
 */
@Service("goodsService")
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, Goods> implements GoodsService {
    @Resource
    private UserOrderDao userOrderDao;

    @Override
    public boolean insert(GoodsDTO dto) {
        return BeanUtil.copyProperties(dto, Goods.class).insert();
    }

    @Override
    public boolean update(Long id, GoodsDTO dto) {
        Goods goods = BeanUtil.copyProperties(dto, Goods.class);
        goods.setId(id);
        return goods.updateById();
    }

    @Override
    public boolean delete(Long id) {
        return removeById(id);
    }

    @Override
    public GoodsVO query(Long id) {
        Goods goods = getById(id);
        GoodsVO goodsVO = BeanUtil.copyProperties(goods, GoodsVO.class);
        //是否已购买
        List<Long> buy = userOrderDao.isBuy(Collections.singletonList(id), UserUtils.getOpenId());
        goodsVO.setIsBuy(buy.contains(id) ? 1 : 0);

        return goodsVO;
    }

    @Override
    public PageVO<GoodsVO> page(GoodsPageQuery query) {
        Page<Goods> page = Db.lambdaQuery(Goods.class)
                .eq(query.getCategoryId() != null, Goods::getCategoryId, query.getCategoryId())
                .like(StringUtils.isNotBlank(query.getGoodsName()), Goods::getGoodsName, query.getGoodsName())
                .page(query.toPage());

        if (CollectionUtils.isEmpty(page.getRecords())) {
            return new PageVO<>(page, GoodsVO.class);
        }

        //是否已购买
        List<Long> idList = page.getRecords().stream().map(Goods::getId).toList();
        List<Long> buy = userOrderDao.isBuy(idList, UserUtils.getOpenId());

        PageVO<GoodsVO> result = new PageVO<>(page, GoodsVO.class);
        for (GoodsVO goodsVO : result.getList()) {
            goodsVO.setIsBuy(buy.contains(goodsVO.getId()) ? 1 : 0);
        }

        return result;
    }
}

